package controllers

import play.api.mvc._
import play.api.routing.JavaScriptReverseRouter
import tool.{FormTool, Tool}

import java.io.File
import javax.inject.Inject
import implicits.Implicits._
import upickle.default._

import scala.collection.immutable.SeqMap
import shared.Pojo._
import shared.pojo.Pojo.HeatmapData
import utils.Utils

import java.nio.file.Files
import scala.concurrent.ExecutionContext.Implicits.global

/**
 * Created by yz on 16/9/2021
 */
class AppController @Inject()(cc: ControllerComponents)(
) extends AbstractController(cc) {

  def toIndex = Action { implicit request =>
    Ok(views.html.index())
  }

  def toRef = Action { implicit request =>
    val files = Tool.refDir.myListFiles.map(_.getName.fileNamePrefix)
    Ok(views.html.reference(files))
  }

  def exp741 = Action { implicit request =>
    Ok(views.html.expression.exp741())
  }

  def exp344 = Action { implicit request =>
    Ok(views.html.expression.exp344())
  }

  def expH2 = Action { implicit request =>
    Ok(views.html.expression.expH2())
  }

  def heatmapData = Action { implicit request =>
    val data = FormTool.fileNameForm.bindFromRequest().get
    val file = new File(Tool.dataDir, data.fileName)
    val lines = file.xlsxLines()
    val x = lines.head.drop(1).distinct
    val y = lines.map(_.head).drop(1).reverse.distinct
    val map = lines.drop(1).flatMap { columns =>
      val rowName = columns.head
      columns.drop(1).zip(x).map { case (value, columnName) =>
        if (value.trim.nonEmpty) {
          (rowName, columnName) -> value
        } else {
          (rowName, columnName) -> null
        }
      }
    }.toSeqMap
    val z = y.map { rowName =>
      x.map { colName =>
        map((rowName, colName))
      }
    }
    val response = HeatmapData(x = x, y = y, z = z)
    Ok(writeJs(response))
  }

  def nwkData = Action { implicit request =>
    val data = FormTool.fileNameForm.bindFromRequest().get
    val file = new File(Tool.dataDir, data.fileName)
    Ok(ujson.Obj("str" -> file.str))
  }

  def downloadTree = Action { implicit request =>
    val data = FormTool.svgForm.bindFromRequest().get
    val dataFile = Files.createTempFile("tmp", ".svg").toFile
    val str = data.svgHtml.replaceAll("</svg>", "\n" + Utils.phylotreeCss + "</svg>")
    str.toFile(dataFile)
    Ok.sendFile(dataFile, onClose = () => {
      Files.deleteIfExists(dataFile.toPath)
    }).withHeaders(
      CACHE_CONTROL -> "max-age=3600",
      CONTENT_DISPOSITION -> "attachment; filename=tree.svg",
      CONTENT_TYPE -> "application/x-download"
    )
  }

  def javascriptRoutes = Action { implicit request =>
    Ok(
      JavaScriptReverseRouter("jsRoutes")(
        controllers.routes.javascript.GenomeController.searchByGeneId,
        controllers.routes.javascript.GenomeController.getAllGeneIds,
        controllers.routes.javascript.GenomeController.searchByGeneName,
        controllers.routes.javascript.GenomeController.getAllGeneNames,
        controllers.routes.javascript.GenomeController.searchByRegion,
        controllers.routes.javascript.GenomeController.getAllChrs,
        controllers.routes.javascript.GenomeController.searchByKeyword,
        controllers.routes.javascript.GenomeController.getBasicInfo,
        controllers.routes.javascript.GenomeController.getAllBasic,

        controllers.routes.javascript.AnnoController.getAnnoByServer,
        controllers.routes.javascript.AnnoController.getSelect2Values,
        controllers.routes.javascript.AnnoController.getAnnoById,
        controllers.routes.javascript.AnnoController.getDetailInfo,

        controllers.routes.javascript.Basic344Controller.allByServer,
        controllers.routes.javascript.Basic344Controller.select2Values,
        controllers.routes.javascript.Basic344Controller.searchByGeneId,
        controllers.routes.javascript.Basic344Controller.searchByRegion,
        controllers.routes.javascript.Basic344Controller.allGeneIds,
        controllers.routes.javascript.Basic344Controller.allChrs,
        controllers.routes.javascript.Basic344Controller.detailInfo,
        controllers.routes.javascript.Basic344Controller.basicInfo,

        controllers.routes.javascript.MarkerController.getFileData,


        controllers.routes.javascript.ToolsController.blast,
        controllers.routes.javascript.ToolsController.blastResultBefore,
        controllers.routes.javascript.ToolsController.blastResult,
        controllers.routes.javascript.ToolsController.downloadByName,
        controllers.routes.javascript.ToolsController.downloadByRange,
        controllers.routes.javascript.ToolsController.seqQuery,
        controllers.routes.javascript.ToolsController.seqMultipleQuery,
        controllers.routes.javascript.ToolsController.keggEnrich,
        controllers.routes.javascript.ToolsController.goEnrich,
        controllers.routes.javascript.ToolsController.muscle,
        controllers.routes.javascript.ToolsController.primer,

        controllers.routes.javascript.ToolController.getFileData,
        controllers.routes.javascript.ToolController.getXlsxFileData,


      )
    ).as("text/javascript")

  }


}
